import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Upload,
  Modal,
  Row,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { POINT_CONVERSION_COMPRESSED } from 'constants';
import maps from 'qqmap';
import Col from 'antd/es/col';
const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { Search } = Input;
@connect(({ user, shops, loading }) => ({
  user,
  shops,
  submitting: loading.effects['shops/fetchSubmitShopForm'],
}))
@Form.create()
class BasicForms extends PureComponent {
  state = {
    uploading: false,
    previewVisible: false,
    previewImage: '',
    fileList: [],
    map: {},
    mapModal: false,
    address: '湖北省宜昌市伍家岗区夷陵大道188号',
    latitude: 30.680403,
    longitude: 111.308101,
    keyword: '', //地图检索关键字
    markers: [],
  };
  showMapModal = () => {
    this.setState({
      mapModal: true,
    });
    this.initQQMap();
  };
  handleOk = e => {
    const { address, latitude, longitude } = this.state;
    const { shops = {}, dispatch } = this.props;
    const { shopDetail } = shops;
    shopDetail.shop_address = address;
    shopDetail.shop_location = JSON.stringify([latitude, longitude]);
    dispatch({
      type: 'shop/editShopDetail',
      payload: shopDetail,
    });
    this.setState({
      mapModal: false,
    });
  };

  handleCancelMap = e => {
    this.setState({
      mapModal: false,
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handleChange = ({ fileList }) => this.setState({ fileList });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  uploadPhoto = () => {
    const { fileList } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    formData.append('picture', fileList[fileList.length - 1]);
    dispatch({
      type: 'shops/uploadShopPhoto',
      payload: formData,
      callback: (status, url) => {
        console.log(status);
        if (status === 'success') {
          fileList[fileList.length - 1].url = url;
          console.log(fileList);
          this.setState({
            fileList: fileList,
          });
        } else {
          fileList.pop();
          this.setState({
            fileList: fileList,
          });
        }
      },
    });
  };

  componentDidMount() {
    const { fileList } = this.state;
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'shops/fetchAllShopSortList',
    });
  }

  handleSubmit = e => {
    const { fileList } = this.state;
    const { shops = {}, dispatch, form } = this.props;
    const { shopDetail = {} } = shops;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let shopCoursel = [];
        fileList.forEach((item, index) => {
          shopCoursel.push(item.url);
        });
        values.shop_coursel = JSON.stringify(shopCoursel);
        values.shop_location = shopDetail.shop_location;
        values.id = shopDetail.id;
        dispatch({
          type: 'shops/fetchSubmitShopForm',
          payload: values,
        });
      }
    });
  };

  beforeUpload = file => {
    this.setState(state => ({
      fileList: [...state.fileList, file],
    }));
  };
  //地图初始化的方法
  initQQMap = () => {
    const { markers } = this.state;
    let that = this;

    //设置中心坐标
    let tarLat = 30.680403;
    let tarLng = 111.308101;
    //初始化地图
    maps.init('BA7BZ-ZALCX-RRY4S-TKL45-IXNO7-IEF5I', () => {
      // 初始化经纬度，最开始的点
      let myLatlng = new qq.maps.LatLng(tarLat, tarLng);
      // 设置地图属性
      let myOptions = {
        zoom: 16,
        center: myLatlng,
        mapTypeId: qq.maps.MapTypeId.ROADMAP,
      };
      // 创建地图，绑定dom
      this.map = new qq.maps.Map(document.getElementById('container'), myOptions);
      const map = this.map;

      const geocoder = new qq.maps.Geocoder({
        complete: function(result) {
          map.setCenter(result.detail.location);
          for (let i in markers) {
            markers[i].setMap(null);
          }
          var marker = new qq.maps.Marker({
            map: map,
            position: result.detail.location,
          });
          markers.push(marker);
          that.setState({
            address: result.detail.address,
            markers: markers,
          });
        },
      });
      //绑定单击事件添加参数
      qq.maps.event.addListener(map, 'click', function(event) {
        var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
        geocoder.getAddress(latLng);

        that.setState({
          latitude: event.latLng.getLat(),
          longitude: event.latLng.getLng(),
        });
      });
    });
  };

  SearchMapByWord = e => {
    const that = this;
    const { keyword } = this.state;
    const { markers } = this.state;
    const map = this.map;
    e.preventDefault();
    //设置Poi检索服务，用于本地检索、周边检索
    const searchService = new qq.maps.SearchService({
      location: '宜昌',
      autoExtend: true,
      //检索成功的回调函数
      complete: function(results) {
        //设置回调函数参数
        var pois = results.detail.pois;
        var infoWin = new qq.maps.InfoWindow({
          map: map,
        });
        console.log(pois);
        var latlngBounds = new qq.maps.LatLngBounds();
        for (var i = 0, l = pois.length; i < l; i++) {
          var poi = pois[i];
          //扩展边界范围，用来包含搜索到的Poi点
          latlngBounds.extend(poi.latLng);

          (function(n) {
            let marker = new qq.maps.Marker({
              map: map,
            });
            marker.setPosition(pois[n].latLng);

            marker.setTitle(i + 1);
            markers.push(marker);

            qq.maps.event.addListener(marker, 'click', function() {
              if (markers) {
                for (i in markers) {
                  markers[i].setMap(null);
                }
                markers.length = 0;
              }

              let marker = new qq.maps.Marker({
                position: pois[n].latLng,
                map: map,
              });
              markers.push(marker);
              that.setState({
                latitude: pois[n].latLng.getLat(),
                longitude: pois[n].latLng.getLng(),
                address: pois[n].address,
                markers: markers,
              });
            });
          })(i);
        }
        //调整地图视野
        map.fitBounds(latlngBounds);
      },
      //若服务请求失败，则运行以下函数
      error: function() {
        alert('出错了。');
      },
    });
    searchService.setLocation('宜昌');
    searchService.search(keyword);
  };
  handleSearchChange = e => {
    console.log(e.target.value);
    this.setState({
      keyword: e.target.value,
    });
  };
  render() {
    const { previewVisible, previewImage, fileList, address, keyword } = this.state;
    const { shops = {}, submitting } = this.props;
    const { shopDetail = {}, shopSort } = shops;
    const {
      form: { getFieldDecorator },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );

    return (
      <PageHeaderWrapper title={<FormattedMessage id="menu.shoplist.addshop" />}>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.img' })}>
              <Upload
                listType="picture-card"
                fileList={fileList}
                onPreview={this.handlePreview}
                onChange={this.handleChange}
                customRequest={this.uploadPhoto}
                beforeUpload={this.beforeUpload}
              >
                {fileList.length >= 3 ? null : uploadButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
              </Modal>
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.name' })}>
              {getFieldDecorator('shop_name', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'shop.name.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.name.placeholder' })} />)}
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.address' })}>
              {getFieldDecorator('shop_address', {
                rules: [
                  {
                    message: formatMessage({ id: 'validation.title.required' }),
                  },
                ],
                initialValue: address,
              })(
                <Search
                  placeholder="请选择地址"
                  enterButton="选择地址"
                  onSearch={this.showMapModal}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.contact' })}>
              {getFieldDecorator('shop_number', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.contact.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.contact.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.eshop' })}>
              {getFieldDecorator('shop_eshop', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.eshop.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.eshop.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.vrsite' })}>
              {getFieldDecorator('shop_vrsite', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.vrsite.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.vrsite.placeholder' })} />)}
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.website' })}>
              {getFieldDecorator('shop_website', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.website.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.website.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.businesshour' })}>
              {getFieldDecorator('shop_businesshour', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.businesshour.placeholder' }),
                  },
                ],
              })(<Input placeholder={formatMessage({ id: 'shop.businesshour.placeholder' })} />)}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.sortname' })}>
              {getFieldDecorator('sort_id', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'shop.sortname.placeholder' }),
                  },
                ],
              })(
                <Select>
                  {shopSort.map((item, index) => (
                    <Option key={index} value={item.id}>
                      {item.title}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.intro' })}>
              {getFieldDecorator('shop_intro', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.intro.placeholder' }),
                  },
                ],
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder={formatMessage({ id: 'shop.intro.placeholder' })}
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={formatMessage({ id: 'shop.vipprivilege' })}>
              {getFieldDecorator('shop_vipprivilege', {
                rules: [
                  {
                    message: formatMessage({ id: 'shop.vipprivilege.placeholder' }),
                  },
                ],
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder={formatMessage({ id: 'shop.vipprivilege.placeholder' })}
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.save" />
              </Button>
            </FormItem>
          </Form>
          <Modal
            title="选择地址"
            visible={this.state.mapModal}
            onOk={this.handleOk}
            onCancel={this.handleCancelMap}
            width="80%"
          >
            <div>
              <Row gutter={20}>
                <Col md={6}>
                  <Input
                    placeholder="请输入位置"
                    name="keyword"
                    onChange={this.handleSearchChange}
                  />
                </Col>
                <Col md={2}>
                  <Button type="primary" onClick={this.SearchMapByWord}>
                    搜索
                  </Button>
                </Col>
                <Col md={6}>
                  <p>当前位置：{address}</p>
                </Col>
              </Row>
            </div>
            <div id="container" style={{ height: 600 }} />
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForms;
